from typing import Optional
from fastapi import status
from fastapi import Header, HTTPException, Request
from fastapi.exceptions import RequestValidationError
from .exception import BusinessException
from .token import jwt_get_current_user
from pydantic import BaseModel, Field

from functools import wraps

LANGUAGE_CODE_EXCHANGE = {
    'zh_CN': 'chinese',
    'en_US': 'english',
    'es_ES': 'spanish',
    'ca_ES': 'catalan'
}


# class RequestHeaders(BaseModel):
#     token: str = Field(None, description="The authentication token")
#     lang: str = Field("en", description="Language setting")
#     custom_field: str = Field("default_value", description="A custom field with a default value")
#
#
# def get_request_headers(
#         token: str = Header(None),
#         lang: str = Header("en"),
#         custom_field: str = Header("default_value")
# ) -> RequestHeaders:
#     return RequestHeaders(token=token, lang=lang, custom_field=custom_field)


def set_lang(f):
    """
    对odoo env配置语言
    """

    @wraps(f)
    async def decorated_function(*args, **kwargs):
        env = kwargs.get('env')
        lang = kwargs.get('Accept_Language')

        if lang is None:
            raise RequestValidationError("Lang header missing")
        if lang not in LANGUAGE_CODE_EXCHANGE:
            raise BusinessException(code='ORM0001')

        env = env(context=dict(env.context, lang=lang))
        kwargs['env'] = env
        response = await f(*args, **kwargs)
        return response

    return decorated_function


def verify_token(f):
    """
    在使用对token进行校验
    """

    @wraps(f)
    async def decorated_function(*args, **kwargs):
        env = kwargs.get('env')
        token = kwargs.get('token')
        lang = kwargs.get('Accept_Language')

        if not token:
            raise RequestValidationError("验证失败")
        else:
            res = jwt_get_current_user(token)
            if res['code'] != 200:
                raise RequestValidationError(res['code'])
            else:
                env = env(context=dict(env.context, lang=lang))
                kwargs['env'] = env
                response = await f(*args, **kwargs)
                return response

    return decorated_function
